package com.hq.user.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hq.user.entity.SysUser;
import com.hq.user.service.impl.SysUserServiceImpl;
import com.hq.user.utils.Base64Utils;
import com.hq.user.utils.R;
import com.hq.user.vo.Login;
import com.hq.user.vo.SaveNewUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * 用户接口
 *
 * @param
 * @author huqiang
 * @date 2022/2/10 13:47
 * @return
 */
@RestController
@RequestMapping("/sysUser")
public class SysUserController {
    @Autowired
    private SysUserServiceImpl sysUserService;

    @GetMapping
    public R getPage(Page page, SysUser sysUser) {
        return R.ok(sysUserService.page(page, Wrappers.query(sysUser)));
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(sysUserService.getById(id));
    }

    @PostMapping
    @Transactional
    public R Save(@RequestBody SaveNewUser saveNewUser) {
        saveNewUser.setPassword(Base64Utils.encode(saveNewUser.getPassword()));
        sysUserService.saveSysUserRole(saveNewUser);
        return R.ok(sysUserService.saveNewUser(saveNewUser));
    }

    @PutMapping
    public R update(@RequestBody SysUser sysUser) {
        return R.ok(sysUserService.updateById(sysUser));
    }

    @DeleteMapping("/{id}")
    public R remove(@PathVariable String id) {
        return R.ok(sysUserService.removeById(id));
    }

    @PostMapping("/login")
    public R login(@RequestBody Login login) {
        SysUser sysUser = new SysUser();
        return R.ok(sysUserService.getOne(Wrappers.query(sysUser).lambda()
                .eq(SysUser::getUsername, login.getName())
                .eq(SysUser::getPassword, Base64Utils.encode(login.getPassword()))));
    }
}